package com.tc.shiro.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class IpUtils {

    public static String getBrowserIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotBlank(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            int index = ip.indexOf(",");// 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.isNotBlank(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }

	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getHeader("Proxy-Client-IP");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getHeader("WL-Proxy-Client-IP");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
			if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip))
				ip = request.getRemoteAddr();
		}

		if (StringUtils.isNotBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
			int index = ip.indexOf(",");// 多次反向代理后会有多个ip值，第一个ip才是真实ip
			if (index != -1)
				ip = ip.substring(0, index);
		}
		return ip;
	}
}
